const arr = [
    {id:1, name: "i1"},
    {id:2, name: "i2",parentId: 1},
    {id:5, name: "i5",parentId: 1},
    {id:3, name: "i3",parentId: 2},
    {id:4, name: "i4",parentId: 3},
]

function transform(arr) {
    const result = {};

    function findObjById(objIn,id) {
        if (null == objIn) {
            objIn = result;
        }
        if (objIn.id == id) {
            return objIn;
        }
        // 查找children
        const children = objIn.children;
        for (const child of children) {
            return findObjById(child,id);
        }
        return null;
    }

    for (const v of arr) {
        // 如果没有parentId，那么它就是顶层对象
        if (v.parentId == undefined) {
            result.children = [];
            Object.assign(result,v);
        } else {
            const obj = findObjById(null,v.parentId)
            if (obj) {
                if (!obj.children) {
                    obj.children = [];
                }
                obj.children.push(v);
            }
        }
    }

    return result;
}

const result = transform(arr);
console.log(JSON.stringify(result));